var app = getApp();
var utils = require('../../utils/utils.js');
var config = require('../../config.js');
var server = require('../../utils/server.js');
var apis = require("../../utils/api.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrlZ: '../image/idcard/idcard_z.png',
    disabled: true,
    option: [],
    selectedOption: '',
    isClickOcr: false,
    isOcrOver: false,
    paramZ: '',
    show1: false,
    show2: false,
    checkAll: true,
    auth: true, //是否授权
    check1: false, //是否点击了人像面
    ctx: null, //拍照实例
    done: false,
    batchNumber: null,
    buttons3: [{
      text: '取消'
    }, {
      text: '确认'
    }], //对话框按钮
    dialogShow3: false, //是否显示对话框
    dataList: [],
    sortingPortNumber: 1,
    base64Data: '',
    isShowEdit: false,
    photoAddress: '',
    key_text: '',
    newNoteDescription: [],
    reStart: false,
    lastIndex: '',
    showSwitch: false,
    hideSwitch: true,
    flash: 'off',
    isToast: false,
    isEdit: false,
    bgColor: '#ffffff', // 初始颜色为白色
    isPressed1: false,
    isPressed2: false
  },

  onTouchStart: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#f1f1f1'; // 设置为灰色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  onTouchEnd: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#ffffff'; // 恢复为白色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  handleTouchStart1() {
    this.setData({
      isPressed1: true
    });
  },

  handleTouchEnd1() {
    this.setData({
      isPressed1: false
    });
  },

  handleTouchStart2() {
    this.setData({
      isPressed2: true
    });
  },

  handleTouchEnd2() {
    this.setData({
      isPressed2: false
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCameraAuth();
    this.setData({
      ctx: wx.createCameraContext()
    })
  },

  /**
   * 关闭摄像机
   */
  done() {
    this.setData({
      done: true,
    });
  },

  /**
   * 授权获取摄像头使用权限
   */
  getCameraAuth() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success: () => {
              this.data.auth = true;
            },
            fail: () => {
              this.setData({
                dialogShow3: true
              });
            },
          });
        } else {
          this.data.auth = true;
        }
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let flash = utils.checkCurrentTime()
    this.setData({
      flash
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  retake() {
    if (this.data.isClickOcr && !this.data.isOcrOver) {
      return
    }
    this.chooseImg()
  },

  //点击正面照弹出相机
  chooseImg() {
    // 清除历史缓存

    let _this = this
    if (app.globalData.userInfo.authStatus != 1) {
      utils.showToast('您还未正式通过企业认证，请稍后再试')
    } else {
      _this.setData({
        isClickOcr: false
      })
      wx.showLoading({
        title: '',
        mask: true,
      });
      wx.getSetting({
        success: (res) => {
          wx.hideLoading();
          if (res.authSetting && !res.authSetting['scope.camera']) {
            this.setData({
              dialogShow3: true, //是否显示对话框
            });
          } else {
            this.setData({
              check1: true,
            });
          }
        },
      });
    }
  },

  /**
   * @description: 选择分拣口
   * @param {type}
   * @return:
   */
  bindPickerChange: function (e) {
    let _this = this
    let selectedOption = _this.data.options[e.detail.value]
    let sortingPortNumber = selectedOption.substring(0, selectedOption.indexOf('号'));
    _this.setData({
      selectedOption,
      sortingPortNumber
    })
  },

  /**
   * @description: 获取编码
   * @param {type}
   * @return:
   */
  bindBmInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('编码长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialNumber'] = value;
    _this.setData({
      isEdit: false,
      dataList: newItems
    })
  },

  /**
   * @description: 获取物料批次号
   * @param {type}
   * @return:
   */
  bindWlpcInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('物料批次号长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialBatchNumber'] = value;
    _this.setData({
      isEdit: false,
      dataList: newItems
    })
  },

  /**
   * @description: 获取数量
   * @param {type}
   * @return:
   */
  bindSlInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    let dataList = _this.data.dataList;
    const reg = /^(?!0\d)\d+(\.\d+)?$/;
    if (!reg.test(value)) {
      utils.showToast('请您输入非零整数')
      dataList[index]['quantity'] = '';
    } else {
      dataList[index]['quantity'] = parseInt(value);
    }
    _this.setData({
      isEdit: false,
      dataList: dataList
    })
  },

  /**
   * @description: 获取分拣批次号
   * @param {type}
   * @return:
   */
  bindBatchNumber: function (e) {
    let _this = this
    let value = e.detail.value
    _this.setData({
      batchNumber: value
    })
  },

  /**
   * @description: 取消拍照
   * @param {type}
   * @return:
   */
  cancel() {
    this.setData({
      check1: false,
    });
  },

  /**
   * @description: 正面拍摄
   * @param {type}
   * @return:
   */
  takePhoto: function () {
    this.setData({
      base64Data: '',
      imgUrlZ: '',
      reStart: false,
      dataList: [],
      batchNumber: '',
      selectedOption: '',
      isShowEdit: false
    });
    this.data.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          check1: false,
        });
        this.getBase64Data(res.tempImagePath).then((da) => {
          let base64Data = da.data;
          base64Data = wx.arrayBufferToBase64(
            wx.base64ToArrayBuffer(base64Data)
          );
          this.setData({
            base64Data: base64Data,
            imgUrlZ: `data:image/jpg;base64,${base64Data}`,
            show1: true,
            reStart: true
          });
          app.globalData.idCardFront = base64Data;
          wx.hideLoading()
        });
        wx.showLoading({
          title: '上传中',
          mask: true,
        });
        this.setData({
          isEdit: true
        })
      },
      fail: (res) => {
        console.log("res:" + JSON.stringify(res))
        this.setData({
          check1: false,
        });
      },
      complete: (res) => {
        console.log("complete:" + JSON.stringify(res))
        wx.hideLoading()
      },
    });
    // 设置图片批次号，一笔请求一个
    let randomNumberStr = utils.generateTimeReqestNumber()
    this.setData({
      batchNumber: randomNumberStr
    })
  },


  /**
   * @description: 点击识别按钮
   * @param {type}
   * @return:
   */
  clickOcr: function () {
    var _this = this;
    if (_this.data.isClickOcr && !_this.data.isOcrOver) {
      return
    }
    _this.setData({
      isClickOcr: true,
      isOcrOver: false
    })
    _this.clearCache()
    if (_this.data.show1) {
      _this.toOcr()
    } else {
      utils.showToast("请上传图片")
    }
  },

  parseVariables(var1, var2, var3) {
    const variables = [var1, var2, var3];
    console.log('第一步', variables)
    // 找出最大长度的数组
    let maxLength = 0;
    variables.forEach(variable => {
      if (Array.isArray(variable)) {
        maxLength = Math.max(maxLength, variable.length);
      } else if (typeof variable === 'boolean') {
        // 将布尔值视作空数组
        maxLength = Math.max(maxLength, 0);
      } else {
        // 对于其他类型（如字符串、数字等），视为单一元素
        maxLength = Math.max(maxLength, 1);
      }
    });

    // 创建结果数组
    const results = variables.map(variable => {
      if (Array.isArray(variable)) {
        return variable; // 如果是数组，直接返回
      } else if (typeof variable === 'boolean') {
        return new Array(maxLength).fill(''); // 布尔值处理为数组
      } else if (variable === undefined || variable === null) {
        return new Array(maxLength).fill(''); // 为空处理
      } else {
        return new Array(maxLength).fill(variable); // 其他类型处理为数组
      }
    });

    // 按照 maxLength 和内容阐明具体的结果
    results.forEach((result, index) => {
      if (result.length < maxLength) {
        const fillCount = maxLength - result.length;
        results[index] = result.concat(new Array(fillCount).fill(''));
      }
    });
    console.log('第二步', results)

    // 输出结果
    const dataList = results[0].map((id, index) => ({
      materialNumber: results[0][index], // 将字符串转换为整数
      materialBatchNumber: results[1][index], // 从 orders 数组中获取订单信息
      quantity: results[2][index]
    }));
    console.log('第三步', dataList)
    return dataList;
  },


  toOcr() {
    let _this = this;
    var params = {
      "base64_image": _this.data.base64Data,
      "batchNum": _this.data.batchNumber
    };
    var api = apis.processImage
    utils.showLoading('数据请求中...')
    wx.request({
      url: config.xwurl + api,
      method: 'POST',
      data: params,
      timeout: 60000,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        wx.hideLoading()
        if (res.statusCode == 200) {
          let data = res.data
          try {
            // 先判断ocr返回的结果中"keyWordList"字段是否存在且有值
            if (!data.hasOwnProperty('keyWordList') || _this.isEmpty(data['keyWordList'])) {
              _this.diyModel('请拍摄清晰完整的图片')
              return
            }
            let keyWordList = data.keyWordList
            let key_text = data.key_text
            let imagePath = data.imagePath
            let match1 = utils.findKeyMappingValueByobject(keyWordList, '物料编码')
            console.log('match1', match1)
            let match2 = utils.findKeyMappingValueByobject(keyWordList, '批次')
            console.log('match2', match2)
            let match3 = utils.findKeyMappingValueByobject(keyWordList, '数量')
            console.log('match3', match3)
            if (!match1 && !match3) {
              utils.showToast('图片未能清晰识别，请重试')
              return
            }
            const dataList = _this.parseVariables(match1, match2, match3);
            console.log('dataList格式化成功', dataList)
            let newNoteDescription = utils.processString(key_text)
            let showSwitch = match2.length > 0 ? true : false
            _this.setData({
              photoAddress: imagePath,
              dataList: dataList,
              key_text: key_text,
              newNoteDescription: newNoteDescription,
              isShowEdit: true,
              reStart: false,
              isEdit: true,
              showSwitch: showSwitch,
              hideSwitch: !showSwitch
            });
            _this.listWithPendingCount()
          } catch (error) {
            _this.diyModel('为提高准确率，请重新拍摄更清晰的图片进行识别')
            return
          }
        } else {
          _this.diyModel('系统开小差了!')
        }

      },
      fail: function (res) {
        wx.hideLoading()
        _this.diyModel('网络超时,请保持手机网络畅通并重新识别')
      },
      complete: function (res) {
        wx.hideLoading()
        _this.setData({
          isClickOcr: false,
          isOcrOver: false
        })
      }
    })
  },

  // 创建物料信息
  bindSubmit() {
    wx.showModal({
      title: '温馨提示',
      content: '是否保存并提交',
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          let _this = this
          let materialInfoList = [];
          let originalArray = _this.data.dataList;
          if (originalArray.length === 0) {
            utils.showToast('请您先录入物料信息')
            return
          }
          // 字段分拣批次号格式必须合法
          if (batchNumber) {
            const regex = /^(\d{2}|\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/;
            if (!regex.test(batchNumber)) {
              utils.showToast(`分拣批次号格式验证失败：${batchNumber} 不符合 (YY|YYYY)MMDD 格式。`)
              return
            }
          }
          for (let i = 0; i < originalArray.length; i++) {
            let item = originalArray[i];
            let newItem = {};
            newItem.id = ""
            // 必填校验
            if (!item['materialNumber'] || !item['quantity']) {
              utils.showToast('请您先将信息填写完整')
              return
            }
            // 值合法性校验
            if (!Number.isInteger(Number(item['quantity']))) {
              utils.showToast('数量输入有误')
              return
            }
            newItem.materialNumber = item['materialNumber'];
            newItem.materialBatchNumber = item['materialBatchNumber'] != undefined ? item['materialBatchNumber'] : '';
            newItem.quantity = item['quantity'];
            newItem.enterpriseId = app.globalData.userInfo.entId;
            newItem.deliveryNoteId = '';
            newItem.sortingStatus = 2;
            materialInfoList.push(newItem);
          }
          // 拼接描述
          let newNoteDescription = _this.data.newNoteDescription
          for (let i = 0; i < newNoteDescription.length; i++) {
            let item = newNoteDescription[i];
            item = "<view>" + item + "</view>"
            newNoteDescription[i] = item
          }
          let noteDescription = newNoteDescription.join('')

          // 隐藏批次号时，上传字段全部传空
          let newDataList = []
          if (_this.data.showSwitch && _this.data.hideSwitch) {
            newDataList = materialInfoList.map(item => {
              // 如果对象中有isFLag属性，则将其值置为空
              if (item.hasOwnProperty('materialBatchNumber')) {
                return {
                  ...item,
                  materialBatchNumber: ''
                };
              }
              return item;
            });
          }

          let params = {
            "deliveryNote": {
              "entCustomerId": app.globalData.userInfo.entId,
              "id": '',
              "batchNumber": _this.data.batchNumber,
              "noteDescription": noteDescription,
              "photoAddress": _this.data.photoAddress,
              "sortingPortNumber": _this.data.sortingPortNumber
            },
            "materialInfoList": newDataList.length > 0 ? newDataList : materialInfoList
          }
          console.log(params)
          let url = apis.createCombind
          server.postRequest(config.xburl, url, params,
            function (res) {
              _this.setData({
                photoAddress: '',
                dataList: [],
                isShowEdit: false,
                show1: false,
                sortingPortNumber: 1,
                base64Data: '',
                key_text: '',
                newNoteDescription: [],
                reStart: false,
                isEdit: false
              });
              let params = {
                type: 'ocr',
                tip: '保存提交成功！'
              }
              wx.navigateTo({
                url: '/pages/Result/Result?value=' + JSON.stringify(params),
              })
            },
            function (err) {
              utils.showToast(err)
            })

        }
      }
    })
  },

  bindMsInput(e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    const newItems = [..._this.data.newNoteDescription];
    newItems[index] = value;
    _this.setData({
      newNoteDescription: newItems
    })
  },

  /**
   * @description: 将图片转成base64
   * @param {type}
   * @return:
   */
  getBase64Data: function (path) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: path,
        encoding: 'base64',
        success(res) {
          resolve(res);
        },
        fail(res) {
          reject(res);
        },
      });
    });
  },

  /**
   * @description: 用户不允许相机授权
   * @param {type}
   * @return:
   */
  error: function (e) {
    console.log(e + '相机初始化授权');
    this.setData({
      check1: false,
      auth: false,
    });
    this.setData({
      dialogShow3: true, //是否显示对话框
    });
  },

  /**
   * @description: 引导用户打开相机授权
   * @param {type}
   * @return:
   */
  openCameraSetting: function () {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting && !res.authSetting['scope.camera']) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting && res.authSetting['scope.camera']) {
                this.setData({
                  auth: true,
                });
                wx.showToast({
                  title: '您已授权使用摄像头',
                  icon: 'none',
                });
              } else {
                this.setData({
                  dialogShow3: true, //是否显示对话框
                });
              }
            },
          });
        } else {}
      },
    });
  },

  /**
   * @description: 获取用户授权提示
   * @param {type}
   * @return:
   * @Date Changed:
   */
  tapDialogButton3: function (e) {
    switch (e.detail.index) {
      case 0:
        this.setData({
          dialogShow3: false, //是否显示对话框
        });
        break;
      case 1:
        this.setData({
          dialogShow3: false, //是否显示对话框
        });
        this.openCameraSetting();
        break;
    }
  },

  /**
   * @description: 清除上传图片的缓存
   * @param {type}
   * @return:
   * @Date Changed:
   */
  clearCache() {
    let _this = this
    _this.setData({
      dataList: [],
      key_text: '',
      newNoteDescription: '',
      isShowEdit: false
    });
  },


  // 添加新项函数
  bindAddRow() {
    let _this = this
    let array = _this.data.dataList
    let showSwitch = _this.data.showSwitch
    let newItem = []
    let dataList = []
    if (array.length === 0) {
      if (showSwitch) {
        dataList = [{
          materialNumber: '',
          quantity: '',
          materialBatchNumber: ''
        }]
      } else {
        dataList = [{
          materialNumber: '',
          quantity: ''
        }]
      }

    } else {
      // 获取第一个元素的键
      const keys = Object.keys(array[0]);
      // 创建新对象，所有值为空字符串
      newItem = keys.reduce((obj, key) => {
        obj[key] = '';
        return obj;
      }, {});
      dataList = [...array, newItem]
    }
    _this.setData({
      dataList
    })
  },


  isEmpty(value) {
    // 检查是否为null或undefined
    if (value === null || value === undefined) {
      return true;
    }

    // 检查是否为数组或字符串
    if (Array.isArray(value)) {
      return true;
    }

    // 检查是否为对象
    if (typeof value === 'object') {
      return Object.keys(value).length === 0;
    }

    // 其他类型(如数字、布尔值)视为非空
    return false;
  },

  bindDelete(e) {
    wx.showModal({
      title: '温馨提示',
      content: '是否删除',
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          let _this = this
          const index = e.currentTarget.dataset.index;
          let dataList = _this.data.dataList
          if (dataList.length == 1) {
            utils.showToast('已经是最后一项了')
            return
          }
          dataList.splice(index, 1)
          setTimeout(function () {
            utils.showToast('已删除')
          }, 100);
          _this.setData({
            dataList: dataList,
            lastIndex: ''
          })
        }
      }
    })
  },

  // 预览图片
  previewImage(e) {
    let _this = this
    wx.previewImage({
      current: 'data:image/jpg;base64,' + _this.data.base64Data,
      urls: ['data:image/jpg;base64,' + _this.data.base64Data]
    });
  },


  listWithPendingCount() {
    let _this = this;
    var prams = {}
    let api = apis.listWithPendingCount;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let data = res.data
        const options = data.map(item => `${item.sortingPortNumber}号口 待分拣数量：${item.pendingCount}`);
        const minIndex = data.reduce((minIndex, currentObj, currentIndex) => {
          if (currentObj.pendingCount < data[minIndex].pendingCount) {
            return currentIndex;
          }
          return minIndex;
        }, 0);
        _this.setData({
          options: options,
          selectedOption: options[minIndex],
          sortingPortNumber: data[minIndex]['sortingPortNumber']
        })
      },
      function (err) {
        utils.showToast(err)
      })
  },

  diyModel(content) {
    wx.showModal({
      title: '提示',
      content: content,
      confirmText: '重试',
      complete: (res) => {
        if (res.cancel) {
          return
        }

        if (res.confirm) {
          this.setData({
            isClickOcr: true,
            isOcrOver: false
          })
          this.toOcr()
        }
      }
    })
  },

  toSumView() {
    let _this = this
    let dataList = _this.data.dataList
    let len = dataList.length
    let total = 0;
    if (dataList.length === 0) {
      utils.showToast('请先录入物料信息')
      return
    }
    dataList.forEach(item => {
      // 值合法性校验
      if (!Number.isInteger(Number(item['quantity']))) {
        utils.showToast('数量输入有误')
        return
      }
      // 将数量转换为整数并累加
      total += parseInt(item.quantity) || 0;
    });
    let content = `${len}个物料，共计${total}件`
    wx.showModal({
      title: '',
      content: content,
      showCancel: false,
      complete: (res) => {
        if (res.confirm) {

        }
      }
    })
  },

  switchChange() {
    let _this = this
    _this.setData({
      hideSwitch: !_this.data.hideSwitch
    })
  },
})